<?php
namespace App\Admin\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Attachment;

/**
 * 附件上传接口
 * :admin-api-path/upload
 * 
 */
class UploadController extends Controller
{

	public function __invoke(Request $request)
	{
		if( $request->isMethod('GET') ){
			return view('admin.upload');
		}

		if( !$request->hasFile('file') ){
			throw new \Exception("未检测到要上传的文件");
		}

		$file = $request->file('file');

		if( !$file->isValid() ){
			throw new \Exception("文件验证失败");
		}

		// 拆分出大概类型和具体类型 video/mp4 video/avi image/gif
		list($probably, $specific) = explode('/', $file->getClientMimeType());

		// 储存
		$disk 	       = 'public';
		$storage_path  = in_array($probably, ['image', 'video', 'audio']) ? $probably : 'other' ; // 储存目录
		$hashName      = $file->hashName();         // 储存文件名
		$file->storeAs($storage_path, $hashName, $disk);

		// 写入数据库
		$attachment = new Attachment();
		$attachment->disk_name 		= $disk;
		$attachment->hash 			= hash_file('md5', $file->getRealPath());
		$attachment->storage_path   = $storage_path;
		$attachment->object_name    = $hashName;
		$attachment->suffix 		= $file->extension();
		$attachment->mime_type      = $file->getClientMimeType();
		$attachment->origin_name    = $file->getClientOriginalName();
		$attachment->size_byte      = $file->getSize();// 文件大小
		$attachment->size_info      = byteToUnit($file->getSize());
		$attachment->save();

		$storage = Storage::disk($disk);


		if( $request->input('attachment') == 'no' ){
			return response([
				'code' => 0,
				'data' => [
					'path' => $storage_path.'/'.$hashName,
					'url' => $storage->url($storage_path.'/'.$hashName),
				],
			]);
		}

		return [
			'code' => 0,
			'data' => [
				'attachment' => $attachment,
				'object' => [
					'root' => $attachment->root, 
					'path' => $attachment->path, 
					'url'  => $attachment->link, 
				]
			],
		];
	}



}
